/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package proyecto2;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
 *
 * @author damian
 */
public class MainWindow extends javax.swing.JFrame implements Observer {

    /**
     * Creates new form MainWindow
     */
    int num_Tanque = 4;
    int num_Avion = 3;
    int num_Barco = 2;
    int num_Granada = 15;
    int puntos = 0, punsi = 0;
    ArrayList<Celda> lista;
    ArrayList<Celda> listaOponente;
    ArrayList<Objeto> listaObjeto;
    int filag = -1;
    int columnag = -1;
    final int alto_celda = 40;
    final int ancho_celda = 40;
    Image[] iconos_tanque;
    Image[] iconos_avion;
    Image[] iconos_barco;
    ImageIcon icono_granada;
    ImageIcon icono_bandera;
    String host, puerto;
    boolean isServer, listo = false, listoOponente = false, miturno = false;
    Servidor server;
    Cliente cliente;
    VConexion vcone;

    public MainWindow() {
        initComponents();

        btnTanque.setText(String.valueOf(num_Tanque));
        btnAvion.setText(String.valueOf(num_Avion));
        btnBarco.setText(String.valueOf(num_Barco));
        btnGranada.setText(String.valueOf(num_Granada));
        //vcon.setVisible(true);


        lista = new ArrayList<>();
        listaOponente = new ArrayList<>();
        listaObjeto = new ArrayList<>();
        pnlCampo.setPreferredSize(new Dimension(10 * ancho_celda * 2 + 30, 10 * alto_celda));
        pnlCampo.add(campo(10, 10, lista));
        pnlCampo.add(campoOponente(10, 10));
        pnlCampo.setPreferredSize(new Dimension(10 * ancho_celda * 2 + 30, 10 * alto_celda));
        this.setBounds(this.getX(), this.getY(),
                pnlBotones.getWidth() + pnlCampo.getPreferredSize().width,
                jPanel1.getHeight() + pnlCampo.getPreferredSize().height);
        File tanque = new File("./src/proyecto2/tanque_imagen.png");
        File avion = new File("./src/proyecto2/avion.png");
        File barco = new File("./src/proyecto2/acorazado1.png");
        iconos_tanque = Celda.recortar(tanque, 2);
        iconos_avion = Celda.recortar(avion, 3);
        iconos_barco = Celda.recortar(barco, 3);
        icono_granada = new ImageIcon("./src/proyecto2/granada.jpg");
        icono_bandera = new ImageIcon("./src/proyecto2/bandera.jpg");

        lblInfo.setText("Arrastre los componentes hacia su campo.");

    }

    public void vcone() {
        final VConexion vcon = new VConexion();
        vcone = vcon;
        final MainWindow aux = this;
        vcon.setLocationRelativeTo(null);
        vcon.setVisible(true);
        vcon.getBtnCon().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    puerto = vcon.getTxtPuerto().getText();
                    host = vcon.getTxtIP().getText();
                    isServer = vcon.getRbtnServidor().isSelected();
                    if (isServer) {
                        aux.server = new Servidor(Integer.parseInt(puerto));

                        //aux.server.ejecutarServidor();
                        aux.server.addObserver(aux);
                        aux.setTitle("Servidor");
                    } else {
                        aux.cliente = new Cliente(host, Integer.parseInt(puerto));
                        //aux.cliente.ejecutarCliente();
                        aux.cliente.addObserver(aux);
                        aux.setTitle("Cliente");
                    }
                } catch (NumberFormatException numberFormatException) {
                }

            }
        });

    }

    public void actualizar() {
        btnTanque.setText(String.valueOf(num_Tanque));
        btnAvion.setText(String.valueOf(num_Avion));
        btnBarco.setText(String.valueOf(num_Barco));
        btnGranada.setText(String.valueOf(num_Granada));
        if (!(num_Avion == 0 && num_Barco == 0 && num_Tanque == 0)) {
            btnGranada.setEnabled(false);
        } else {
            if (!listo) {
                btnGranada.setEnabled(true);
                listo = true;
                lblInfo.setText("Esperando que el otro jugador esté listo para iniciar.");
                /**
                 * Informar al oponente que está listo para jugar *
                 */
                if (isServer) {
                    server.enviarDatos("Listo||");
                    miturno = true;
                    lblInfo.setText("Su turno.");
                } else {
                    cliente.enviarDatos("Listo||");
                    miturno = false;
                    lblInfo.setText("Esperando al otro jugador...");
                }
            }
        }
    }

    public JPanel campo(int celdas_h, int celdas_v, final ArrayList<Celda> lista) {
        JPanel pnl = new JPanel();
        pnl.setLayout(new GridLayout(celdas_v, celdas_h, 0, 0));
        int k = 0;
        Celda celda;
        for (int i = 0; i < celdas_v; i++) {
            for (int j = 0; j < celdas_h; j++) {
                celda = new Celda(k, j, i);
                lista.add(celda);
                pnl.add(celda);
                celda.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseEntered(MouseEvent e) {
                        filag = ((Celda) e.getSource()).fila;
                        columnag = ((Celda) e.getSource()).columna;
                    }

                    @Override
                    public void mouseExited(MouseEvent e) {
                        filag = -1;
                        columnag = -1;
                    }
                });
                k++;
            }
        }
        return pnl;
    }

    // GRANaDA
    public JPanel campoOponente(int celdas_h, int celdas_v) {
        JPanel pnl = new JPanel();

        pnl.setLayout(new GridLayout(celdas_v, celdas_h, 0, 0));
        int k = 0;
        Celda celda;
        for (int i = 0; i < celdas_v; i++) {
            for (int j = 0; j < celdas_h; j++) {
                celda = new Celda(k, j, i);
                listaOponente.add(celda);
                pnl.add(celda);
                celda.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseEntered(MouseEvent e) {
                        filag = ((Celda) e.getSource()).fila;
                        columnag = ((Celda) e.getSource()).columna;
                    }

                    @Override
                    public void mouseExited(MouseEvent e) {
                    }
                });
                k++;
            }
        }
        return pnl;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        puntuacion = new javax.swing.JLabel();
        pnlBotones = new javax.swing.JPanel();
        btnTanque = new javax.swing.JButton();
        btnAvion = new javax.swing.JButton();
        btnBarco = new javax.swing.JButton();
        btnGranada = new javax.swing.JButton();
        pnlCampo = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        lblInfo = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Juego");
        setPreferredSize(new java.awt.Dimension(584, 574));

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        puntuacion.setText("0");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1)
                .addGap(142, 142, 142)
                .addComponent(puntuacion)
                .addContainerGap(751, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(puntuacion))
                .addContainerGap())
        );

        getContentPane().add(jPanel1, java.awt.BorderLayout.NORTH);

        pnlBotones.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        pnlBotones.setEnabled(false);
        pnlBotones.setLayout(new java.awt.GridLayout(5, 1, 5, 5));

        btnTanque.setIcon(new javax.swing.ImageIcon(getClass().getResource("/proyecto2/tanque_icon.png"))); // NOI18N
        btnTanque.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        btnTanque.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnTanque.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnTanque.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                btnTanqueMouseReleased(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                btnTanqueMouseEntered(evt);
            }
        });
        btnTanque.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                btnTanqueMouseDragged(evt);
            }
        });
        btnTanque.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTanqueActionPerformed(evt);
            }
        });
        pnlBotones.add(btnTanque);

        btnAvion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/proyecto2/f.png"))); // NOI18N
        btnAvion.setText("dd");
        btnAvion.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        btnAvion.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAvion.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAvion.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                btnAvionMouseReleased(evt);
            }
        });
        btnAvion.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                btnAvionMouseDragged(evt);
            }
        });
        btnAvion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAvionActionPerformed(evt);
            }
        });
        pnlBotones.add(btnAvion);

        btnBarco.setIcon(new javax.swing.ImageIcon(getClass().getResource("/proyecto2/barquito.jpg"))); // NOI18N
        btnBarco.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        btnBarco.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnBarco.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnBarco.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                btnBarcoMouseReleased(evt);
            }
        });
        btnBarco.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                btnBarcoMouseDragged(evt);
            }
        });
        btnBarco.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBarcoActionPerformed(evt);
            }
        });
        pnlBotones.add(btnBarco);

        btnGranada.setIcon(new javax.swing.ImageIcon(getClass().getResource("/proyecto2/granada.jpg"))); // NOI18N
        btnGranada.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        btnGranada.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnGranada.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGranada.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                btnGranadaMouseReleased(evt);
            }
        });
        btnGranada.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                btnGranadaMouseDragged(evt);
            }
        });
        pnlBotones.add(btnGranada);

        getContentPane().add(pnlBotones, java.awt.BorderLayout.WEST);

        pnlCampo.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        pnlCampo.setPreferredSize(new java.awt.Dimension(690, 320));
        pnlCampo.setLayout(new java.awt.GridLayout(1, 2, 30, 0));
        getContentPane().add(pnlCampo, java.awt.BorderLayout.CENTER);

        java.awt.FlowLayout flowLayout1 = new java.awt.FlowLayout(java.awt.FlowLayout.LEFT);
        flowLayout1.setAlignOnBaseline(true);
        jPanel2.setLayout(flowLayout1);

        lblInfo.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblInfo.setForeground(new java.awt.Color(0, 153, 204));
        lblInfo.setText("...");
        jPanel2.add(lblInfo);

        getContentPane().add(jPanel2, java.awt.BorderLayout.SOUTH);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnTanqueMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnTanqueMouseDragged
    }//GEN-LAST:event_btnTanqueMouseDragged

    private void btnTanqueMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnTanqueMouseEntered
    }//GEN-LAST:event_btnTanqueMouseEntered

    private void btnTanqueMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnTanqueMouseReleased

        for (int l = 0; l < lista.size(); l++) {
            if (filag == lista.get(l).fila) {
                if (columnag == lista.get(l).columna) {
                    System.out.println(columnag);
                    if (filag < 9) {
                        if (lista.get(l).getIcon() == null && lista.get(l + 1).getIcon() == null && num_Tanque > 0) {
                            lista.get(l).setIcon(new ImageIcon(iconos_tanque[0]));
                            lista.get(l + 1).setIcon(new ImageIcon(iconos_tanque[1]));
                            ArrayList<Celda> aux = new ArrayList<>();
                            aux.add(lista.get(l));
                            aux.add(lista.get(l + 1));
                            listaObjeto.add(new Objeto(aux, "Tanque"));
                            num_Tanque--;
                            actualizar();
                        }
                    }
                }
            }
        }
    }//GEN-LAST:event_btnTanqueMouseReleased

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
//        this.setBounds(this.getX(), this.getY(), this.getWidth(), this.getHeight() + 1);
        if (isServer) {
            server.enviarDatos("test|| ");
        } else {
            cliente.enviarDatos("test|| ");
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void btnAvionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAvionActionPerformed
    }//GEN-LAST:event_btnAvionActionPerformed

    private void btnAvionMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnAvionMouseDragged
    }//GEN-LAST:event_btnAvionMouseDragged

    private void btnAvionMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnAvionMouseReleased
        for (int l = 0; l < lista.size(); l++) {
            if (filag == lista.get(l).fila) {
                if (columnag == lista.get(l).columna) {
                    if (filag < 8) {
                        if (lista.get(l).getIcon() == null && lista.get(l + 1).getIcon() == null && lista.get(l + 2).getIcon() == null && num_Avion > 0) {
                            lista.get(l).setIcon(new ImageIcon(iconos_avion[0]));
                            lista.get(l + 1).setIcon(new ImageIcon(iconos_avion[1]));
                            lista.get(l + 2).setIcon(new ImageIcon(iconos_avion[2]));
                            ArrayList<Celda> aux = new ArrayList<>();
                            aux.add(lista.get(l));
                            aux.add(lista.get(l + 1));
                            aux.add(lista.get(l + 2));
                            listaObjeto.add(new Objeto(aux, "Avion"));
                            num_Avion--;
                            actualizar();
                        }
                    }
                }
            }
        }
    }//GEN-LAST:event_btnAvionMouseReleased

    private void btnGranadaMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnGranadaMouseDragged
    }//GEN-LAST:event_btnGranadaMouseDragged

    private void btnGranadaMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnGranadaMouseReleased
        System.out.println(listo + " " + listoOponente + " " + miturno);
        if (listo && listoOponente && miturno && num_Granada > 0) {
            for (int i = 0; i < listaOponente.size(); i++) {
                if (filag == listaOponente.get(i).fila) {
                    if (columnag == listaOponente.get(i).columna) {
                        if (listaOponente.get(i).getIcon() == null && num_Granada > 0) {
                            listaOponente.get(i).setIcon(icono_granada);
                            num_Granada--;
                            actualizar();
                            if (isServer) {
                                server.enviarDatos("Granada||" + String.valueOf(filag)
                                        + "||" + String.valueOf(columnag) + "||");
                            } else {
                                cliente.enviarDatos("Granada||" + String.valueOf(filag)
                                        + "||" + String.valueOf(columnag) + "||");
                            }
                            miturno = false;
                            if (num_Granada <= 0) {
                                btnGranada.setText("Finalizar");
                                lblInfo.setText("De clic en finalizar.");
                            } else {
                                lblInfo.setText("Esperando oponente...");
                            }
                        }
                    }
                }
            }
        } else if (num_Granada == 0) {
            if (puntos > Integer.parseInt(puntuacion.getText())) {
                JOptionPane.showMessageDialog(null, "Perdedor");
            } else if (puntos < Integer.parseInt(puntuacion.getText())) {
                JOptionPane.showMessageDialog(null, "Ganador");
            } else {
                JOptionPane.showMessageDialog(null, "Empate");
            }
        } else {
            JOptionPane.showMessageDialog(rootPane, "No puede atacar aun.");
        }

    }//GEN-LAST:event_btnGranadaMouseReleased

    private void btnBarcoMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnBarcoMouseDragged
    }//GEN-LAST:event_btnBarcoMouseDragged

    private void btnBarcoMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnBarcoMouseReleased
        ArrayList<Celda> aux = new ArrayList<>();
        boolean a = false, b = false;
        int cbanderda = -1, cbarco = -1;
        for (int l = 0; l < lista.size(); l++) {

            if (filag == lista.get(l).fila) {
                if (columnag == lista.get(l).columna) {
                    if (filag < 8 && columnag > 0) {
                        if (lista.get(l).getIcon() == null && lista.get(l + 1).getIcon() == null && lista.get(l + 2).getIcon() == null) {
                            cbarco = l;
                            a = true;
                        }
                    }
                }
            }
            if (filag + 1 == lista.get(l).fila) {
                if (columnag - 1 == lista.get(l).columna) {
                    if (lista.get(l).getIcon() == null) {
                        cbanderda = l;
                        b = true;
                    }
                }
            }
        }
        if (a && b && num_Barco > 0) {
            lista.get(cbarco).setIcon(new ImageIcon(iconos_barco[0]));
            lista.get(cbarco + 1).setIcon(new ImageIcon(iconos_barco[1]));
            lista.get(cbarco + 2).setIcon(new ImageIcon(iconos_barco[2]));
            aux.add(lista.get(cbarco));
            aux.add(lista.get(cbarco + 1));
            aux.add(lista.get(cbarco + 2));

            lista.get(cbanderda).setIcon(icono_bandera);
            aux.add(lista.get(cbanderda));
            listaObjeto.add(new Objeto(aux, "Barco"));
            num_Barco--;
            actualizar();
        }
    }//GEN-LAST:event_btnBarcoMouseReleased

    private void btnBarcoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBarcoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btnBarcoActionPerformed

    private void btnTanqueActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTanqueActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btnTanqueActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainWindow().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAvion;
    private javax.swing.JButton btnBarco;
    private javax.swing.JButton btnGranada;
    private javax.swing.JButton btnTanque;
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JLabel lblInfo;
    private javax.swing.JPanel pnlBotones;
    private javax.swing.JPanel pnlCampo;
    private javax.swing.JLabel puntuacion;
    // End of variables declaration//GEN-END:variables

    public Celda buscar(int f, int c, ArrayList<Celda> l) {
        Celda cel = null;
        for (int i = 0; i < l.size(); i++) {
            if (f == l.get(i).fila) {
                if (c == l.get(i).columna) {
                    cel = l.get(i);
                    break;
                }
            }
        }
        return cel;
    }

    public boolean ataque(int f, int c, int punsi, ArrayList<Objeto> l) {
        boolean a = false,b=false;
        Objeto o = null;
        for (int i = 0; i < l.size(); i++) {
            Objeto obj = l.get(i);
            for (int j = 0; j < obj.listaCeldas.size(); j++) {
                Celda cel = obj.listaCeldas.get(j);
                if (cel.fila == f && cel.columna == c && obj.vivo) {
                    a = true;
                    b=true;
                    o = obj;
                    break;
                } else if(cel.fila == f && cel.columna == c){
                    b=true;
                    
                    break;
                }
            }
        }
        if (a && b) {
            for (int i = 0; i < o.listaCeldas.size(); i++) {
                Celda cel = o.listaCeldas.get(i);
                cel.setBackground(Color.ORANGE);
                cel.setBorder(BorderFactory.createLineBorder(Color.ORANGE));
                o.vivo = false;
                puntos++;

                //puntuacion.setText(String.valueOf(punsi));
            }
            if (isServer) {
                server.enviarDatos("Puntos||" + String.valueOf(puntos));
            } else {
                cliente.enviarDatos("Puntos||" + String.valueOf(puntos));
            }

        } else if (!a){
            if (!b) {
                buscar(f, c, lista).setBackground(Color.GREEN);
                puntuacion.setText(String.valueOf(punsi));
            }

        }
        JOptionPane.showMessageDialog(rootPane, "Su turno");
        lblInfo.setText("Su turno.");
        boolean fin = true;
        for (int i = 0; i < l.size(); i++) {
            Objeto objeto = l.get(i);
            if (objeto.vivo) {
                fin = false;
                break;
            }
        }
        if (fin) {
            JOptionPane.showMessageDialog(null, "Perdedor");
            if (isServer) {
                server.enviarDatos("Ganador||");
            } else {
                cliente.enviarDatos("Ganador||");
            }
        }
        return a;
    }

    @Override
    public void update(Observable o, Object arg) {
        try {
            this.setVisible(true);
            vcone.setVisible(false);
            String mensaje = "sin menjsae";
            String[] datos;
            Celda cel = null;
            int f, c;
            if (server != null) {
                System.out.println("hoa");
                mensaje = server.msg + "||";
                System.out.println(mensaje);

            } else {
                System.out.println("asf");
                mensaje = cliente.msg + "||";
                System.out.println(mensaje);

            }
            datos = mensaje.split("\\|\\|");
            System.out.println("Msn:" + mensaje);
            System.out.print("Datos: ");
            for (int i = 0; i < datos.length; i++) {
                System.out.print(datos[i] + " ");
            }
            System.out.println("");
            switch (datos[0]) {
                case "Listo":
                    listoOponente = true;
                    break;
                case "Granada":
                    f = Integer.parseInt(datos[1]);
                    c = Integer.parseInt(datos[2]);
                    //punsi = Integer.parseInt(datos[3]);
                    //cel=buscar(f, c, lista);
                    ataque(f, c, punsi, listaObjeto);
                    miturno = true;
                    break;
                case "Ganador":
                    JOptionPane.showMessageDialog(null, "Ganador");
                    break;
                case "Puntos":
                    puntuacion.setText(datos[1]);
                    punsi = Integer.parseInt(datos[1]);
                    break;
                default:
                    break;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}
